package cn.yang.controller;

import cn.yang.domain.Questions;
import cn.yang.domain.UserAnswers;
import cn.yang.domain.UserScores;
import cn.yang.domain.dto.UserAnswerDto;
import cn.yang.service.QuestionsService;
import cn.yang.service.UserAnswersService;
import cn.yang.service.UserScoresService;
import cn.yang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/answer")
public class AnswerController {
    @Autowired
    QuestionsService questionService;
    @Autowired
    UserAnswersService userAnswerService;
    @Autowired
    UserScoresService userScoreService;
    @PostMapping("/submitAnswers")
    public Result submitAnswers(@RequestBody List<UserAnswerDto> answers) {
        System.out.println(123);
        int totalScore = 0;
        for (UserAnswerDto answer : answers) {
            // 保存用户的每个答案
            UserAnswers userAnswer = new UserAnswers();
            userAnswer.setUserId(answer.getUserId());
            userAnswer.setQuestionId(answer.getQuestionId());
            userAnswer.setSelectedOption(answer.getSelectedOption());

            // 检查是否正确
            Questions question = questionService.getById(answer.getQuestionId());
            if (question != null && question.getCorrectOption().equals(answer.getSelectedOption())) {
                userAnswer.setIsCorrect(1);
                totalScore++;
            } else {
                userAnswer.setIsCorrect(0);
            }

            userAnswerService.save(userAnswer);
        }

        // 保存用户得分
        UserScores userScore = new UserScores();
        userScore.setUserId(answers.get(0).getUserId());
        userScore.setScore(totalScore);
        userScoreService.save(userScore);

        return Result.success("答案提交成功", totalScore);
    }

}
